package org.geekbang.thinking.in.spring.bean.lifecycle;

import org.geekbang.thinking.in.spring.ioc.overview.domain.User;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * Bean 实例化生命周期示例
 *
 * @author: wangsiqi
 * @date: 2021/10/31
 */
public class BeanInstantiationAwareBeanLifecycleDemo {

    public static void main(String[] args) {
        executeApplicationContext();

        System.out.println("---------------------------------------------------------------------------");

        // executeBeanFactory();
    }

    private static void executeBeanFactory() {
        DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
        // 添加 BeanPostProcessor 实例
        // 方式一：
        // beanFactory.addBeanPostProcessor(new MyInstantiationAwareBeanPostProcessor());
        // 方式二：通过 XML 注入

        // 基于 XML 资源的 BeanDefinitionReader 实现
        XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);

        // 加载 BeanDefinition
        String[] locations = new String[]{"META-INF/bean-constructor-dependency-injection-context.xml",
                "META-INF/dependency-lookup-context.xml"};
        int beanCounts = beanDefinitionReader.loadBeanDefinitions(locations);
        System.out.println("已加载  BeanDefinition 数量：" + beanCounts);

        // 查找 Bean
        User user = beanFactory.getBean("user", User.class);
        System.out.println("user: " + user);
        User superUser = beanFactory.getBean("superUser", User.class);
        System.out.println("superUser: " + superUser);

        // 构造器注入按照类型注入，resolveDependency
        UserHolder userHolder = beanFactory.getBean("userHolder", UserHolder.class);
        System.out.println("userHolder: " + userHolder);
    }

    public static void executeApplicationContext() {
        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext();

        // 加载 BeanDefinition
        String[] locations = new String[]{"META-INF/bean-constructor-dependency-injection-context.xml",
                "META-INF/dependency-lookup-context.xml"};

        applicationContext.setConfigLocations(locations);
        // 启动应用上下文
        applicationContext.refresh();

        // 查找 Bean
        User user = applicationContext.getBean("user", User.class);
        System.out.println("user: " + user);
        User superUser = applicationContext.getBean("superUser", User.class);
        System.out.println("superUser: " + superUser);

        // 构造器注入按照类型注入，resolveDependency
        UserHolder userHolder = applicationContext.getBean("userHolder", UserHolder.class);
        System.out.println("userHolder: " + userHolder);

        // 关闭应用上下文
        applicationContext.close();
    }


}

